#include "reactor_client.h"
#include <arpa/inet.h>
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <strings.h>
#include "connection.h"
#include "poll_poller.h"
#include "timer_event.h"
#include "trace.h"

reactor_client::reactor_client(const std::string& ip, uint16_t port, int conn_count)
    : ip_(ip), port_(port), conn_count_(conn_count), server_addr_len_(sizeof(struct sockaddr_in))
{
    poller_ = new poll_poller();
    TRACE_DEBUG("ip:%s port:%d", ip_.c_str(), port_);
}

reactor_client::~reactor_client()
{
    if (poller_) {
        delete poller_;
    }
}
void reactor_client::start()
{
    init_server_addr();
    for (int i = 0; i < conn_count_; i++) {
        auto conn                    = std::make_shared<connection>(poller_, server_addr_ptr_);
        all_connections_[conn->fd()] = conn;
        poller_->run_in_loop(std::bind(&connection::connect_server, conn));
    }
    poller_->start();
}

void reactor_client::init_server_addr()
{
    bzero(&server_addr_, sizeof(server_addr_));
    server_addr_.sin_family = AF_INET;
    server_addr_.sin_port   = htons(port_);
    if (inet_pton(AF_INET, ip_.c_str(), &server_addr_.sin_addr) != 1) {
        throw std::runtime_error("inet_pton error");
    }
    server_addr_ptr_ = reinterpret_cast<struct sockaddr*>(&server_addr_);
}
